package com.itheima.reggie.controller;

import com.itheima.reggie.entity.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //1. 获取文件名
        // String name = file.getName();getName方法获得的文件名没有后缀
        String originalFilename = file.getOriginalFilename(); //1.jpg

        //2. 获取文件的拓展名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf(".")); //.jpg

        //3. 使用UUID生成一个全新的名字
        String UUIDFileName = UUID.randomUUID().toString() + suffixName;

        //创建文件存储的目标文件夹
        File dir = new File(path);
        if (!dir.exists()) {
            //文件夹不存在则创建
            dir.mkdirs();
        }

        //把上传文件存储到目标路径上
        File destFile = new File(dir,UUIDFileName);
        file.transferTo(destFile); //把原始文件拷贝到目标位置上

        // 注意：返回的名字一定要是存储在服务器中的文件名，因为前端需要根据名字去访问图片
        return R.success(UUIDFileName);

    }

    @GetMapping("/download")
    public void download(String name,HttpServletResponse response) throws IOException {
        //1. 找到目标文件
        File file = new File(path,name);
        FileInputStream inputStream = new FileInputStream(file);

        //通知浏览器当前输出的类型是图片
        response.setContentType("image/jpeg");

        //获取response的输出流，把图片的资源写出去
        ServletOutputStream outputStream = response.getOutputStream();

        //2. 边读边写
        byte[] buf = new byte[1024];
        int length;
        while ((length = inputStream.read(buf)) != -1) {
            outputStream.write(buf,0,length);
        }

        //3. 关闭资源
        inputStream.close();

    }

}
